package com.smt.modules.bus.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.smt.common.enums.Code;
import com.smt.common.utils.Constant;
import com.smt.common.utils.EnumToKeyUtil;
import com.smt.common.utils.R;
import com.smt.modules.bus.entity.BillEntity;
import com.smt.modules.bus.entity.ConsumptionFileEntity;
import com.smt.modules.bus.entity.GradeEntity;
import com.smt.modules.bus.entity.MemberUserEntity;
import com.smt.modules.bus.service.BillService;
import com.smt.modules.bus.service.ConsumptionFileService;
import com.smt.modules.bus.service.ConsumptionService;
import com.smt.modules.bus.service.GradeService;
import com.smt.modules.bus.vo.ConsumptionFileVo;
import net.bytebuddy.asm.Advice;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zhangyi
 * @date 2018/10/24 10:50
 */
@Service
public class ConsumptionServiceImpl implements ConsumptionService {

    @Autowired
    private BillService billService;

    @Autowired
    private GradeService gradeService;

    @Autowired
    private ConsumptionFileService consumptionService;

    @Override
    public R showIntegral(MemberUserEntity memberUserEntity) {
        Long userId = memberUserEntity.getUserId();

        GradeEntity gradeEntity = gradeService.selectOne(new EntityWrapper<GradeEntity>()
                .eq("member_id", userId));
        return R.ok("获取成功").put("grade", gradeEntity);
    }

    @Override
    public R upgrade(MemberUserEntity memberUserEntity) {

        Long userId = memberUserEntity.getUserId();

        GradeEntity gradeEntity = gradeService.selectOne(new EntityWrapper<GradeEntity>()
                .eq("member_id", userId));
        Integer level = gradeEntity.getLevel();
        Integer integral = gradeEntity.getIntegral();
        BillEntity billEntity = new BillEntity();
        billEntity.setBillTitle("升级账号");
        GradeEntity gradeEntity1 = new GradeEntity();
        if (Constant.LEVEL_1 == (level)) {
            if (integral >= Constant.LEVEL_2) {
                billEntity.setAmount(Constant.LEVEL_J2);
                gradeEntity1.setIntegral(Constant.LEVEL_J2);
                return update(gradeEntity1, billEntity, memberUserEntity, 1) ?
                        R.ok().put(EnumToKeyUtil.toInt(Code.OPERATION_SUCCESS).toString(),"升级成功") :
                        R.error(EnumToKeyUtil.toInt(Code.UPDATE_FAIL),"积分不够");
            }
        } else if (Constant.LEVEL_2 == (level)) {
            if (integral >= Constant.LEVEL_3) {
                billEntity.setAmount(Constant.LEVEL_J3);
                gradeEntity1.setIntegral(Constant.LEVEL_J3);
                return update(gradeEntity1, billEntity, memberUserEntity, 1) ?
                        R.ok().put(EnumToKeyUtil.toInt(Code.OPERATION_SUCCESS).toString(),"升级成功") :
                        R.error(EnumToKeyUtil.toInt(Code.UPDATE_FAIL),"积分不够");
            }
        } else if (Constant.LEVEL_3 == (level)) {
            return R.ok("您需要付费申请");
        } else {
            return R.ok("您已经是最高等级");
        }
        return R.error(EnumToKeyUtil.toInt(Code.APPEND_DATA_ERROR),"升级失败");
    }

    /**
     * 下载付费积分文件
     *
     * @param memberUserEntity
     * @return
     */
    @Override
    public R downloadConsumption(ConsumptionFileVo consumptionFileVo, MemberUserEntity memberUserEntity) {
        Long userId = memberUserEntity.getUserId();
        Integer fileIntegral = consumptionFileVo.getFileIntegral();
        GradeEntity gradeEntity =
                gradeService.selectOne(new EntityWrapper<GradeEntity>().eq("member_id", userId));
        if (gradeEntity.getIntegral() <= fileIntegral) {
            return R.error(EnumToKeyUtil.toInt(Code.APPEND_DATA_ERROR),"积分不够");
        }
        BillEntity billEntity = new BillEntity();
        billEntity.setBillTitle("下载文件");
        GradeEntity consumptionGradeEntity = new GradeEntity();
        consumptionGradeEntity.setIntegral(fileIntegral);
        billEntity.setAmount(consumptionFileVo.getFileIntegral());
        boolean result = update(consumptionGradeEntity, billEntity, memberUserEntity, 2);
        Map<String, Object> map = new ConcurrentHashMap<>();
        map.put("status", result);
        ConsumptionFileEntity fileInfo = consumptionService.selectOne(new EntityWrapper<ConsumptionFileEntity>()
                .eq("id", consumptionFileVo.getId()));
        String fileUrl = fileInfo.getFileUrl();
        map.put("filePath", fileUrl);
        return R.ok().put("result", map);
    }

    /**
     * 升级账号等级，添加消费记录
     *
     * @param gradeEntity
     * @param billEntity
     * @param memberUserEntity
     * @param type 判断是否是否下载还是升级
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    boolean update(GradeEntity gradeEntity, BillEntity billEntity, MemberUserEntity memberUserEntity, Integer type) {
        GradeEntity old = gradeService.selectOne(new EntityWrapper<GradeEntity>()
                .eq("member_id", memberUserEntity.getUserId()));
        Integer oldIntegral = old.getIntegral();
        Integer newIntegral = gradeEntity.getIntegral();
        Integer level = old.getLevel();
        gradeEntity.setMemberId(memberUserEntity.getUserId());
        if (oldIntegral >= newIntegral) {
            gradeEntity.setIntegral(oldIntegral - newIntegral);
            if (type == 1) {
                gradeEntity.setLevel(level + 1);
            } else if (type == 2) {
                gradeEntity.setLevel(level);
            }
            boolean update = gradeService.update(gradeEntity, new EntityWrapper<GradeEntity>()
                    .eq("member_id", memberUserEntity.getUserId()));
            billEntity.setExpenditure(2);
            billEntity.setTransactionName(memberUserEntity.getUsername());
            billEntity.setTransactionTime(DateTime.now().toDate());
            billEntity.setCreateTime(DateTime.now().toDate());
            billEntity.setBusBusinessId(memberUserEntity.getUserId());
            billEntity.setType(1);
            billEntity.setIsReward(2);
            boolean insert = billService.insert(billEntity);
            return insert && update;
        } else {
            return false;
        }
    }
}
